# -*- coding: utf-8 -*-
from __future__ import annotations
import os, json
from dotenv import load_dotenv
load_dotenv()

MOCK = os.getenv("MOCK_LLM", "0") == "1"

def _mock_chat_with_tools(messages: list[dict], tools: list[dict], **kwargs) -> dict:
    # 极简模拟器：如果问题里包含 "2+3" 则触发 sum 工具调用，否则直接返回文本答案。
    last_user = next((m for m in reversed(messages) if m.get("role") == "user"), {})
    content = (last_user.get("content") or "").strip()
    if "2+3" in content:
        return {
            "role": "assistant",
            "content": None,
            "tool_calls": [{
                "id": "call_mock_1",
                "type": "function",
                "function": {"name": "sum", "arguments": json.dumps({"a": 2, "b": 3}, ensure_ascii=False)}
            }]
        }
    return {
        "role": "assistant",
        "content": "这是一个模拟器回答（未调用真实 API）。",
        "tool_calls": []
    }

def chat_with_tools(messages: list[dict], 
                    tools: list[dict], 
                    *, 
                    model: str | None = None, 
                    tool_choice: str = "auto", 
                    **kwargs) -> dict:
    """调用 DeepSeek（OpenAI 兼容）Chat Completions 的 Function Calling。

    返回简化过的 assistant message：
    { "role": "assistant", "content": str|None, "tool_calls": [ {id, type, function:{name,arguments}} ] }
    """
    if MOCK:
        return _mock_chat_with_tools(messages, tools, **kwargs)

    api_key = os.getenv("DEEPSEEK_API_KEY")
    base_url = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
    model = model or os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
    if not api_key:
        raise RuntimeError("缺少 DEEPSEEK_API_KEY。请在 .env 中配置或导出到环境变量。")

    from openai import OpenAI
    client = OpenAI(api_key=api_key, base_url=base_url)
    params = dict(
        model=model,
        messages=messages,
        tools=tools,
        tool_choice=tool_choice,   # "auto" | {"type":"function","function":{"name":"sum"}}
        temperature=kwargs.get("temperature", 0.2),
    )
    resp = client.chat.completions.create(**params)
    msg = resp.choices[0].message

    # 适配：把 OpenAI SDK Message 对象转为 dict（避免上层依赖 SDK 类型）
    out = {
        "role": msg.role,
        "content": msg.content,
        "tool_calls": []
    }
    if getattr(msg, "tool_calls", None):
        for tc in msg.tool_calls:
            out["tool_calls"].append({
                "id": tc.id,
                "type": tc.type,
                "function": {
                    "name": tc.function.name,
                    "arguments": tc.function.arguments,
                }
            })
    return out
